package setting

import (
	"../common"
	"../web"
	"strings"
)

type SetItemTestingObj struct {
	common.BaseHandler
}

func (self *SetItemTestingObj) Prepare() {
	items := *common.FetchAllRowsPtr(
		`SELECT ITEM, ISNULL(DESCRIP,'') 
           FROM SFC_ITEMS(NOLOCK) 
          ORDER BY ITEM`,
		self.Usr.Conn, new(common.ItemDesc))

	self.TmplData["items"] = items
}

func (self *SetItemTestingObj) ParameterCheck() bool {
	c_item := self.Ctx.Params["item"]
	c_para := strings.TrimSpace(self.Ctx.Params["printname"])
	c_test := strings.TrimSpace(self.Ctx.Params["testname"])
	c_freq := strings.TrimSpace(self.Ctx.Params["freqname"])
	c_port := strings.TrimSpace(self.Ctx.Params["ports"])
	c_spec := strings.TrimSpace(self.Ctx.Params["specifi"])
	if c_item == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the item.")
		return false
	}

	testinfo := *common.FetchAllRowsPtr(
		`SELECT ITEM,PARAMETER,TESTNAME,FREQUENCY,PORT,SPECIFICATION
           FROM SFC_ITEMSTEST(NOLOCK) 
          WHERE ITEM=?
          ORDER BY ITEM, IDX`,
		self.Usr.Conn, new(common.PassiveFrequency), c_item)

	self.TmplData["testinfo"] = testinfo

	if c_para == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Parameter.")
		return false
	}
	if c_test == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Test Name.")
		return false
	}
	if c_freq == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Frequency.")
		return false
	}
	if c_spec == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please input the Specification.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, c_item)
	self.Sqlparas = append(self.Sqlparas, c_para)
	self.Sqlparas = append(self.Sqlparas, c_test)
	self.Sqlparas = append(self.Sqlparas, c_freq)
	self.Sqlparas = append(self.Sqlparas, c_port)
	self.Sqlparas = append(self.Sqlparas, c_spec)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{strings.ToUpper(c_item)}

	return true
}

func (self *SetItemTestingObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetItemTest ?, ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func ItemTestSetHandler(ctx *web.Context) {
	self := new(SetItemTestingObj)
	self.Ctx = ctx
	self.Url = "/setitemtest"
	self.Html = "setitemtest.html"
	self.Rightlist = []string{"setitemtest"}
	self.Flashstr = "Set Items: [ %v ] test info finished."
	self.Do(self)
}
